package org.lanqiao.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.lanqiao.pojo.Order;
import org.lanqiao.util.BeanToJsonWriter;
import org.lanqiao.util.SqlUtil;
import org.lanqiao.util.StringUtils;
import org.lanqiao.vo.JsonResultVo;;




@WebServlet("/order/session")
public class QueryLoginInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse resposne) throws ServletException, IOException {
		JsonResultVo<Order> jsonResult=null;
		HttpSession session  =request.getSession(false);
		if(session!=null){
			Object    data =session.getAttribute("loginUserKey");
			if(data!=null){
				//已经登录了
				String  loginUname =StringUtils.toSpaceSting(data);
				String sql="select * from  user  where  username =?";
				List <HashMap<String,Object>>   list = SqlUtil.executeQuery(sql, loginUname);
				if(list!=null && list.size()>0){
					HashMap  row =list.get(0);
					//把登录用户转换为订单用户 
					Order  order =new Order();
					order.setId(String.valueOf(System.currentTimeMillis())); //订单编号  用时间的毫米数临时作为
					order.setUsername(StringUtils.toSpaceSting(row.get("username")));
					order.setName(StringUtils.toSpaceSting(row.get("name")));; //用户表可能没有这个字段，后期加上
					order.setTelphone(StringUtils.toSpaceSting(row.get("telphone")));
					order.setAddress(StringUtils.toSpaceSting(row.get("address"))); //用户表可能没有这个字段，后期加上
					
					
					jsonResult =new  JsonResultVo("200","登录用户",order);
				}
				
				
			}else{
				//没有登录，使用临时用户
					data =	session.getAttribute("buyerKey");
					if(data!=null){
						String  tempUname =StringUtils.toSpaceSting((data));
						Order  order =new Order();
						order.setUsername(tempUname);
						//设置订单编号为当前时间戳
						order.setId(String.valueOf(System.currentTimeMillis()));
						jsonResult =new  JsonResultVo("200","临时用户",order);
					
					
					}
			}
		
			
		}
		//如果没找到数据
		if(jsonResult==null){
			jsonResult	=new  JsonResultVo("404","没有数据");
		}
		//转换Json，写入前端
		BeanToJsonWriter.write(resposne, jsonResult);
		
		
		
	}
}
